<template>
    <div>
        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon
            style="margin-left: 550px;margin-top: 100px;">
            <el-form-item label="登录名" prop="loginName">
                <el-input v-model="form.loginName" placeholder="请输入登录名" maxlength="20" show-word-limit
                    style="width: 300px;" />
            </el-form-item>
            <el-form-item label="密码" prop="passWord">
                <el-input v-model="form.passWord" type="password" placeholder="请输入密码" show-password
                    style="width: 300px;" />
            </el-form-item>
            <el-form-item label="验证码" prop="checkCode">
                <el-input v-model="form.checkCode" style="width: 120px;" />&nbsp;<el-tag class="ml-2" type="success"
                    style="font-size: 14pt;">{{ chcCode }}</el-tag>&nbsp;<el-button type="primary"
                    @click="createCheckCode" plain>换一个</el-button>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="form.savePassword">记住密码</el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="Login(ruleFormRef)">
                    登录
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
//引入组件
import { ref, reactive, onMounted, inject } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from "vue-router"
import type { AxiosStatic } from "axios"

//引入cookies
import Cookies from "cookies-ts"

const cookies = new Cookies()

const axios = inject<AxiosStatic>("axios")

import { useUser } from '@/stores/loginer'

const useCount = useUser();

const router = useRouter()


//变量
const ruleFormRef = ref<FormInstance>()
let form = reactive({
    loginName: "",
    passWord: "",
    checkCode: "",
    savePassword: false
})
//生成的验证码
let chcCode = ref("")
let rules = reactive<FormRules>({
    loginName: [
        { required: true, message: '请输入登录名', trigger: 'blur' },
        { min: 1, max: 20, message: '登录名在1-20个字符之间', trigger: 'blur' },
    ],
    passWord: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    checkCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
    ]
})
//方法
const Login = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (form.checkCode.toLocaleLowerCase() != chcCode.value.toLocaleLowerCase()) {
                ElMessage.error("验证码错误，请重新输入")
                return;
            }
            axios?.post("http://10.31.56.20:8081/api/Login/Login", form).then(res => {
                if (res.data.code == 0) {
                    ElMessage.error(res.data.msg)
                }
                if (res.data.code == 1) {
                    useCount.islogin = true
                    useCount.username = res.data.userName
                    if (form.savePassword) {
                        //保存密码到cookie
                        cookies.set("loginName", form.loginName)
                        cookies.set("password", form.passWord)
                    } else {
                        //未勾选，删除信息
                        cookies.remove("loginName")
                        cookies.remove("password")
                    }
                    ElMessage.success("登录成功，欢迎您：" + res.data.userName)
                    localStorage.setItem('token', res.data.token)
                    router.push("/UserListView")
                } else {
                    ElMessage.error("登录失败")
                }
            })
        } else {
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

//生成验证码
const createCheckCode = () => {
    //数据源
    let scource = "0123456789abcdefghijklmnopqrsduvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    //存放获得随机字母
    let CordArr = [];
    for (let i = 0; i < 4; i++) {
        //随机字符序号
        let index = Math.floor(Math.random() * scource.length)
        CordArr.push(scource[index]);
    }
    //获取生成的验证码
    chcCode.value = CordArr.join("")
}

onMounted(() => {
    createCheckCode();

    // 反填cookie
    if (cookies.get("loginName")) {
        form.loginName = cookies.get("loginName") || ""
        form.passWord = cookies.get("password") || ""
        form.savePassword = true
    }
})

</script>

<style></style>